package com.ity.teamanagement.utils;

import com.ity.teamanagement.code.ImgCode;
import com.ity.teamanagement.exception.ExceptionUtils;
import io.swagger.annotations.ApiModel;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author coderFu
 * @create 2021/6/4
 */
@ApiModel("图片压缩工具类")
public class ImgUtils {
    /**
     *  最小压缩大小
     */
    private static final long LEAST_COMPRESS_SIZE = 1024;

    public static String compressPicForSize(String srcPath, String desPath,
                                            long desFileSize, double accuracy){
        if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(desPath)){
            ExceptionUtils.error(ImgCode.IMG_NOT_EXIST);
        }
        if (!new File(srcPath).exists()){
            ExceptionUtils.error(ImgCode.IMG_NOT_EXIST);
        }
        try{
            File srcFile = new File(srcPath);
            long srcFileSize = srcFile.length();
            //将图片转为jpg格式
            Thumbnails.of(srcPath).scale(1f).toFile(desPath);
            //递归压缩，直到目标文件大小小于desFileSize
            compressPicCycle(desPath,desFileSize,accuracy);
            File desFile = new File(desPath);
        }catch (Exception e){
            ExceptionUtils.error(ImgCode.IMG_COMPRESS_ERROR);
        }
        return desPath;
    }

    private static void compressPicCycle(String desPath, long desFileSize,
                                          double accuracy) throws IOException {
        File srcFileJPG = new File(desPath);
        long srcFileSizeJPG = srcFileJPG.length();
        // 2、判断大小，如果小于指定大小，不压缩；如果大于等于指定大小，压缩
        if (srcFileSizeJPG <= desFileSize * LEAST_COMPRESS_SIZE) {
            return;
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(srcFileJPG);
        int srcWdith = bim.getWidth();
        int srcHeigth = bim.getHeight();
        int desWidth = new BigDecimal(srcWdith).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(srcHeigth).multiply(
                new BigDecimal(accuracy)).intValue();

        Thumbnails.of(desPath).size(desWidth, desHeight)
                .outputQuality(accuracy).toFile(desPath);
        compressPicCycle(desPath, desFileSize, accuracy);
    }



}
